<template>
  <view class="services-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 顶部操作栏 -->
    <view class="header-bar">
      <text class="title">选择服务</text>
      <text class="select-all" @tap="handleSelectAll">
        {{ selectAllLabel }}
      </text>
    </view>

    <!-- 服务列表 -->
    <view class="services-list">
      <view 
        class="service-item" 
        v-for="(item, index) in serviceList" 
        :key="index"
        @tap="selectService(item)"
      >
        <view class="radio-wrapper">
          <view 
            class="custom-radio" 
            :class="{ 'checked': selectedServices.includes(item.id.toString()) }"
          >
            <view class="inner-circle"></view>
          </view>
        </view>
        <view class="service-info">
          <view class="service-icon">
            <image :src="item.imgUrls.split(',')[0]" mode="aspectFit" v-if="item.imgUrls.split(',')[0]"></image>
            <text v-else>{{ item.projectName.charAt(0) }}</text>
          </view>
          <view class="service-detail">
            <text class="service-name">{{ item.projectName }}</text>
            <text class="service-desc">{{ item.projectDesp || '暂无描述' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="bottom-bar">
      <button 
        class="save-btn" 
        :disabled="selectedServices.length === 0"
        @tap="handleSave"
      >保存</button>
    </view>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
  data() {
    return {
      serviceList: [],
      selectedServices: [], // 选中的服务数组
      techId: '' // 添加techId
    }
  },

  computed: {
    // 是否全部选中
    isAllSelected() {
      return this.serviceList.length > 0 && this.selectedServices.length === this.serviceList.length
    },
    // 按钮显示文字：有选中就显示取消全选，否则显示全选
    selectAllLabel () {
      return this.selectedServices.length === 0 ? '全选' : '取消全选'
    }
  },

  onLoad() {
    // 从本地存储获取techId
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      this.techId = userInfo.techId
    }
    this.loadServiceList()
    this.loadSelectedServices()
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    goToServiceDetail(service) {
      uni.navigateTo({
        url: `/pages/technician/service-detail?type=${service.projectName}&id=${service.id}`
      })
    },

    async loadServiceList() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/project/project/listAll`,
          method: 'GET',
          data: {
            status: 1
          }
        })

        if (result.data.code === 200) {
          this.serviceList = result.data.rows.map(item => ({
            ...item,
            id: item.id.toString() // 确保ID是字符串类型
          }))
        } else {
          throw new Error(result.data.msg || '加载失败')
        }
      } catch (err) {
        console.error('加载服务列表失败:', err)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 加载已选择的服务
    async loadSelectedServices() {
      if (!this.techId) {
        console.error('未找到techId')
        return
      }

      try {
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/project/project/technician/${this.techId}`,
          method: 'GET'
        })

        if (result.data.code === 200) {
          // 将已选择的项目ID添加到selectedServices数组中
          this.selectedServices = result.data.rows.map(item => item.id.toString())
        }
      } catch (err) {
        console.error('获取已选择服务失败:', err)
        uni.showToast({
          title: '获取已选择服务失败',
          icon: 'none'
        })
      }
    },

    // 选择服务
    selectService(service) {
      const serviceId = service.id.toString()
      const index = this.selectedServices.indexOf(serviceId)
      if (index === -1) {
        this.selectedServices.push(serviceId)
      } else {
        this.selectedServices.splice(index, 1)
      }
    },

    // 处理全选/取消全选
    handleSelectAll() {
      if (this.selectedServices.length === 0) {
        // 目前没有任何选中 → 全选
        this.selectedServices = this.serviceList.map(service => service.id.toString())
      } else {
        // 有选中项 → 取消全选
        this.selectedServices = []
      }
    },

    // 保存选择的服务
    async handleSave() {
      if (this.selectedServices.length === 0) return
      
      uni.showLoading({
        title: '保存中...'
      })
      
      try {
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/project/project/technician/${this.techId}`,
          method: 'PUT',
          data: {
            projectIds: this.selectedServices.join(',')
          },
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        })
        
        if (result.data.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(result.data.msg || '保存失败')
        }
      } catch (err) {
        console.error('保存服务失败:', err)
        uni.showToast({
          title: err.message || '保存失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.services-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
  
  .header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    
    .title {
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }

    .select-all {
      font-size: 28rpx;
      color: #2B85E4;
      padding: 10rpx 20rpx;
    }
  }
  
  .services-list {
    background: #FFFFFF;
    margin-top: 20rpx;
    
    .service-item {
      display: flex;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #F5F5F5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .radio-wrapper {
        margin-right: 20rpx;
        
        .custom-radio {
          width: 40rpx;
          height: 40rpx;
          border: 2rpx solid #CCCCCC;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &.checked {
            border-color: #2B85E4;
            
            .inner-circle {
              width: 24rpx;
              height: 24rpx;
              background: #2B85E4;
              border-radius: 50%;
            }
          }
        }
      }
      
      .service-info {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 20rpx;

        .service-icon {
          width: 80rpx;
          height: 80rpx;
          background: #F5F5F5;
          border-radius: 12rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          image {
            width: 80rpx;
            height: 80rpx;
            border-radius: 12rpx;
          }

          text {
            font-size: 32rpx;
            color: #666666;
          }
        }

        .service-detail {
          flex: 1;
          
          .service-name {
            font-size: 32rpx;
            color: #333333;
            margin-bottom: 8rpx;
            display: block;
          }
          
          .service-desc {
            font-size: 24rpx;
            color: #999999;
            display: block;
          }
        }
      }
    }
  }

  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .save-btn {
      height: 80rpx;
      line-height: 80rpx;
      background: #2B85E4;
      color: #FFFFFF;
      font-size: 32rpx;
      border-radius: 40rpx;
      
      &[disabled] {
        opacity: 0.6;
      }
      
      &::after {
        border: none;
      }
    }
  }
}
</style> 